<template>
  <div class="app-container">
    <!-- 搜索功能 -->
    <div>
      <el-input
        v-model="nameParam"
        style="width: 200px; margin: 20px 10px 20px 20px"
        placeholder="请输入姓名"
      />
      <el-input
        v-model="accountParam"
        style="width: 200px; margin: 20px 30px 20px 10px"
        placeholder="请输入账号"
      />
      <el-button type="primary" @click="fetchData">搜索</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="100">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="姓名" width="400" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column
        class-name="status-col"
        label="性别"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.sex | statusFilter">{{
            scope.row.sex
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="账号" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.account }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="created_at"
        label="生日"
        width="200"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.birthday }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            style="margin-right: 20px"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-popconfirm
            title="是否删除这行表格？"
            @onConfirm="handleDelete(scope.row)"
            @onCancel="handleCancel()"
          >
            <el-button
              slot="reference"
              size="mini"
              type="danger"
            >删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改用户 -->
    <el-dialog title="修改用户" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="form.account" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-col :span="11">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">完成</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getList, updateUser, deleteUser } from '@/api/userList'
export default {
  filters: {
    statusFilter(sex) {
      const statusMap = {
        male: 'gray',
        female: 'danger'
      }
      return statusMap[sex]
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      // dialog 弹窗参数设置
      dialogVisible: false,

      // 查询
      nameParam: '',
      accountParam: '',

      // dialog
      form: {
        name: '',
        account: '',
        sex: '',
        birthday: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    /**
     * 获取userList数据
     */
    fetchData() {
      this.listLoading = true
      getList({ name: this.nameParam, account: this.accountParam }).then(
        (response) => {
          this.list = response.data.items
          this.listLoading = false
        }
      )
    },

    /**
     * 编辑按钮 点击事件
     */
    handleEdit(row) {
      // 显示 dialog 弹窗
      this.dialogVisible = true
      this.form = JSON.parse(JSON.stringify(row))
    },

    /**
     * 删除按钮点击事件
     * @param {*} row
     */
    handleDelete(row) {
      deleteUser({ id: row.id }).then((res) => {
        if (res.code === 20000) {
          this.$message.success('删除' + res.msg)
          this.fetchData()
        } else {
          this.$message.error('删除' + res.msg)
        }
      })
    },
    // Popconfirm  取消按钮
    handleCancel() {
      this.$message.warning('取消操作')
    },

    /**
     * 修改数据
     */
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (typeof this.form.birthday === 'object') {
            this.form.birthday = this.dateFormat(
              'YYYY-mm-dd',
              this.form.birthday
            )
          }
          updateUser(this.form).then((res) => {
            if (res.code === 20000) {
              this.$message.success('修改' + res.msg)
              this.fetchData()
              this.dialogVisible = false
              this.$refs.form.resetFields()
            } else {
              this.$message.error('修改' + res.msg)
            }
          })
        }
      })
    },

    /**
     * 日期格式化
     * @param {*} fmt 格式格式
     * @param {*} date 时间
     */
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    }
  }
}
</script>

<style scoped></style>
